package com.example.myapplication2.Service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class LocalService extends Service {

    private LocalBinder binder = new LocalBinder();

    private Thread thread;

    private boolean quit=false;

    private int count;

    public LocalService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("服务绑定");
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("服务解绑");
        return super.onUnbind(intent);
    }

    /**
     * 创建Binder对象，返回给客户端即Activity使用，提供数据交换的接口
     */
    public class LocalBinder extends Binder {
        // 声明一个方法，getService。（提供给客户端调用）
        public LocalService getService() {
            System.out.println("LocalBinder返回");
            // 返回当前对象LocalService,这样我们就可在客户端端调用Service的公共方法了
            return LocalService.this;
        }
    }

    /**
     * 公共方法
     * @return
     */
    public int getCount(){
        return count;
    }

    @Override
    public void onCreate() {
        System.out.println("服务创建");
        super.onCreate();

        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 每间隔一秒count加1 ，直到quit为true。
                while (!quit) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        });
        thread.start();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        System.out.println("服务销毁");
        this.quit = true;
        super.onDestroy();
    }
}